package com.itheima.comment.service.impl;

import com.itheima.comment.vo.CommentVo;
import com.itheima.comment.document.Comment;
import com.itheima.comment.document.CommentLike;
import com.itheima.comment.dto.CommentDto;
import com.itheima.comment.dto.CommentLikeDto;
import com.itheima.comment.dto.CommentSaveDto;
import com.itheima.comment.repository.CommentRepository;
import com.itheima.comment.service.CommentService;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发表评论
     *
     * @param dto
     */
    @Override
    public void save(CommentSaveDto dto) {
        //判断是否为匿名
        if (RequestContextUtil.isAnonymous()) {
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }
        //构建pojo
        int loginUserId = Integer.parseInt(RequestContextUtil.getUserId());
        Comment comment = new Comment();
        BeanUtils.copyProperties(dto, comment);
        comment.setLikes(0);
        comment.setReplys(0);
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUserId(loginUserId);

        comment.setHeadImage(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_IMAGE));
        comment.setNickName(RequestContextUtil.getHeader(SystemConstants.LOGIN_USER_NAME));
        comment.setCreatedTime(LocalDateTime.now());
        comment.setUpdatedTime(LocalDateTime.now());
        //保存
        commentRepository.save(comment);
    }

    /**
     * 点赞评论或取消
     *
     * @param dto
     */
    @Override
    public void like(CommentLikeDto dto) {
        //需要判断是否为匿名用户
        if (RequestContextUtil.isAnonymous()) {
            throw new LeadNewsException(HttpCodeEnum.NEED_LOGIN);
        }

        //请求头获取登录用户的id
        long loginUserId = Long.parseLong(RequestContextUtil.getUserId());
        //查询点赞记录是否存在--从mongoDB查
        Query query = Query.query(Criteria.where("userId").is(loginUserId)
                .and("commentId").is(dto.getCommentId()));
        CommentLike commentLike = mongoTemplate.findOne(query, CommentLike.class);

        int updateCount = 0;
        //判断点赞类型
        if (dto.getOperation() == 1) {
            //点赞过了，不能重复点赞，抛异常
            if (null != commentLike) {
                throw new LeadNewsException("已经点赞过了！");
            }
            //否则，添加点赞行为
            commentLike = new CommentLike();
            commentLike.setCommentId(dto.getCommentId());
            commentLike.setUserId(loginUserId);
            mongoTemplate.insert(commentLike);
            updateCount = -1;
        }
        //更新评论中的赞数量
        Query updateQuery = new Query(Criteria.where("id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("likes", updateCount);
        mongoTemplate.findAndModify(updateQuery, update, Comment.class);
    }

    /**
     * 获取文章的评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<CommentVo> loadPage(CommentDto dto) {
        //参数校验
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        List<CommentVo> voList = new ArrayList<>();
        //构建查询条件
        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId())
                .and("createdTime").lt(dto.getMinDate()));
        //每页查询10条
        query.limit(10);
        //设置排序
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);

        if(!StringUtils.isEmpty(comments)){
            //转成vo
            voList = comments.stream().map(CommentVo::build).collect(Collectors.toList());

            //判断是否为匿名用户
            if(!RequestContextUtil.isAnonymous()){
                //登录用户-取出所有评论的id
                List<String> commentIdList = comments.stream().map(Comment::getId).collect(Collectors.toList());
                long loginUserId = Long.parseLong(RequestContextUtil.getUserId());

                //构建条件查询评论点赞表
                Query commentLikeQuery = new Query(Criteria.where("userId").is(loginUserId).and("commentId").in(commentIdList));
                List<CommentLike> commentLikes = mongoTemplate.find(commentLikeQuery, CommentLike.class);

                //判断有结果就标记点赞
                if(!CollectionUtils.isEmpty(commentLikes)){
                    //遍历点赞结果
                    /*for (CommentVo commentVo : voList) {
                        for (CommentLike commentLike : commentLikes) {
                            if(commentVo.getId().equals(commentLike.getCommentId())){
                                commentVo.setOperation(1);
                                break;
                            }
                        }
                    }*/
                    voList.forEach(commentVo ->{
                        commentLikes.forEach(commentLike -> {
                            if(commentVo.getId().equals(commentLike.getCommentId())){
                                commentVo.setOperation(1);
                            }
                        });
                    });
                }

            }
        }
        return voList;
    }
}
